package com.safety51.bootstrap.demo.application.jobhandler;

import com.google.common.base.Stopwatch;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author liuyuancheng
 *
 * @example https://github.dev/xuxueli/xxl-job/tree/master/xxl-job-executor-samples/xxl-job-executor-sample-springboot/src/main
 */
@Component
@Slf4j
public class ExampleJobHandlers {

    @XxlJob(value = "exampleJobHandler",init = "init",destroy = "destroy")
    public ReturnT<String> exampleJobHandler(String param) throws  InterruptedException {
        try {
            XxlJobLogger.log("exampleJobHandler-start");
            Stopwatch stopwatch = Stopwatch.createStarted();
            for (int i = 0; i < 10; i++) {
                Thread.sleep(100);
                log.debug("exampleJobHandler round-{}",i);
            }
            XxlJobLogger.log("exampleJobHandler-finish,cost(seconds)=" + stopwatch.stop().elapsed(TimeUnit.SECONDS));
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            //xxlJob发出的停止线程异常
            if (e instanceof InterruptedException) {
                throw e;
            }
            XxlJobLogger.log("exampleJobHandler-fail:{}", e);
            return ReturnT.FAIL;
        }
    }

    public void init(){
        log.info("exampleJobHandler-inited");
    }
    public void destroy(){
        log.info("exampleJobHandler-destroy");
    }
}
